package Lock_2;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SafeTransfer {
    private final Lock lock1 = new ReentrantLock();
    private final Lock lock2 = new ReentrantLock();

    public void transferAtoB(int amount) {
        boolean gotLock1 = false;
        boolean gotLock2 = false;

        try {
            gotLock1 = lock1.tryLock(100, TimeUnit.MILLISECONDS);
            gotLock2 = lock2.tryLock(100, TimeUnit.MILLISECONDS);

            if (gotLock1 && gotLock2) {
                System.out.println(Thread.currentThread().getName() + " 成功转账 " + amount);
                Thread.sleep(30); // 模拟转账时间
            } else {
                System.out.println(Thread.currentThread().getName() + " 无法获取全部锁，转账失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (gotLock1) lock1.unlock();
            if (gotLock2) lock2.unlock();
        }
    }

    public void transferBtoA(int amount) {
        boolean gotLock1 = false;
        boolean gotLock2 = false;

        try {
            gotLock2 = lock2.tryLock(100, TimeUnit.MILLISECONDS);
            gotLock1 = lock1.tryLock(100, TimeUnit.MILLISECONDS);

            if (gotLock1 && gotLock2) {
                System.out.println(Thread.currentThread().getName() + " 成功转账 " + amount);
                Thread.sleep(30); // 模拟转账时间
            } else {
                System.out.println(Thread.currentThread().getName() + " 无法获取全部锁，转账失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (gotLock1) lock1.unlock();
            if (gotLock2) lock2.unlock();
        }
    }
}

public class 锁超时_避免死锁 {
    public static void main(String[] args) {
        final SafeTransfer transfer = new SafeTransfer();

        // 创建20个A→B转账线程
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                public void run() {
                    transfer.transferAtoB(100);
                }
            }, "A→B转账-" + i).start();
        }

        // 创建20个B→A转账线程
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                public void run() {
                    transfer.transferBtoA(100);
                }
            }, "B→A转账-" + i).start();
        }
    }
}